package blockchain.entity.MerkleTree;

import blockchain.crypto.SHAUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 简化版MerkleTree
 *
 * @author lhr
 */
public class SimpleMerkleTree {
    //按MerkleTree思想计算根结点哈希值
    public static String getTreeNodeHash(List<String> hashList) {
        if (hashList == null || hashList.size() == 0) {
            return null;
        }
        while (hashList.size() != 1) {
            hashList = getTreeNodeList(hashList);
        }
        return hashList.get(0);
    }

    public static List<String> getTreeNodeList(List<String> contentList) {
        List<String> merkleNodeList = new ArrayList<>();
        if (contentList == null || contentList.size() == 0) {
            return merkleNodeList;
        }
        int index = 0, length = contentList.size();
        while (index < length) {
            String left = contentList.get(index++);
            String right = "";
            if (index < length) {
                right = contentList.get(index++);
            }
            //计算左右孩子节点的父节点的哈希值
            String sha2HexValue = SHAUtil.sha256BasedHutool(left + right);
            merkleNodeList.add(sha2HexValue);
        }
        return merkleNodeList;
    }
}
